package com.test.webtest.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.lang.UUID;
import cn.hutool.core.util.RandomUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.test.webtest.dto.LoginFormDTO;
import com.test.webtest.dto.Result;
import com.test.webtest.dto.UserDTO;
import com.test.webtest.entity.User;
import com.test.webtest.mapper.UserMapper;
import com.test.webtest.service.IUserService;
import com.test.webtest.utils.RegexUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import static com.test.webtest.utils.RedisConstants.*;


@Slf4j
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public Result sendCode(String phone, HttpSession session) {
        //1. 校验手机号
        if (RegexUtils.isPhoneInvalid(phone)) {
            //如果不符合，返回错误信息
            return Result.fail("手机号格式错误！");
        }
        //2. 生成验证码
        String code = RandomUtil.randomNumbers(6);

        ////3. 保存验证码到session
        //session.setAttribute("code", code);

        // 3.保存验证码到redis中
        stringRedisTemplate.opsForValue().set(LOGIN_CODE_KEY + phone, code, LOGIN_CODE_TTL, TimeUnit.MINUTES);

        //4. 发送验证码(需要调用阿里云短信平台，这里只做模拟)
        log.info("发送验证码成功，验证码：{}", code);

        //5. 返回ok
        return Result.ok();
    }

    /**
     * 密码登录
     * @param loginForm
     * @param session
     * @return
     */
    @Override
    public Result login(LoginFormDTO loginForm, HttpSession session) {
        // 校验手机号
        if (RegexUtils.isPhoneInvalid(loginForm.getPhone())) {
            return Result.fail("手机号格式错误！");
        }

        String phone = loginForm.getPhone();
        String password = loginForm.getPassword();
        //说明是密码登录
        if (password == null){
            return Result.fail("请输入密码");
        }

        //校验密码
        if (password.length() < 6){
            return Result.fail("密码长度不能小于6位！");
        }

        LambdaQueryWrapper<User> wapper = new LambdaQueryWrapper<>();
        wapper.eq(User::getPassword, password)
                .eq(User::getPhone, phone);
        User user = getOne(wapper);
        if (user == null){
            return Result.fail("用户名或密码错误");
        }
        //登录成功
        String token = loginSuccess(user);


        return Result.ok(token);
    }

    // 登录成功
    public String loginSuccess(User user){
        // 保存用户信息到redis中
        String token = UUID.randomUUID().toString();
        // 保存的是UserDTO
        UserDTO userDTO = BeanUtil.toBean(user, UserDTO.class);

        Map<String, Object> userMap = new HashMap<>();
        userMap.put("id", userDTO.getId().toString());
        userMap.put("nickName", userDTO.getNickName());
        userMap.put("icon", userDTO.getIcon());

        //session.setAttribute("user", userDTO);
        stringRedisTemplate.opsForHash().putAll(LOGIN_USER_KEY + token, userMap);
        //设置过期时间
        stringRedisTemplate.expire(LOGIN_USER_KEY + token, LOGIN_USER_TTL, TimeUnit.MINUTES);

        // 返回token
        return token;
    }
}
